package com.hzsai.nettylearn.server;

import com.hzsai.nettylearn.util.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * hzsai 2019/11/13
 * usage: 同步IO server
 **/
//@Component
public class TimeServer{

    private static final Logger logger = LoggerFactory.getLogger(TimeServer.class);

    @Value("${timeserver.port:1048}")
    private int port;

    @Value("${timeserver.ip:127.0.0.1}")
    private String ip;

    private ServerSocket server = null;

    private boolean runnable = true;

    public TimeServer() {
    }

//    @PostConstruct
    public void postConstruct() throws IOException {
        logger.info(DateTimeUtil.getDate() + "Server: Starting server...");
        server = new ServerSocket(port, 5, InetAddress.getByName(ip));
    }

    /**
     * serversocket启动并接受socket连接请求，将连接socket用线程来处理
     * @throws IOException
     */
    public void start() throws IOException, InterruptedException {
        //Thread.sleep(20000);
        logger.info(DateTimeUtil.getDate() + "Server: Running...");
        while (runnable) {
            Socket socket = server.accept();
            new Thread(new TimeServerHandler(socket)).start();
        }
    }

    /**
     * 停止server
     * @throws IOException
     */
    public void stop() throws IOException {
        runnable = false;
        if (server != null)
            server.close();
    }
}
